<?php
namespace App\Modules\Admin\Controllers;

use App\Http\Requests\Admin\LoginRequest;
use App\Models\Admin\SysUser;
use App\Modules\ModuleBaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Mews\Captcha\Facades\Captcha;

class AuthController extends ModuleBaseController
{
    public function login(LoginRequest $request)
    {
        $user = SysUser::where('username', $request->username)->first();

        if ($user && Hash::check($request->password, $user->password)) {
            $token = $user->createToken('admin-token', ['*'])->plainTextToken;

            // return response()->json(['token' => $token]);
            return $this->responseSuccess([
                "accessToken" => $token,
                "tokenType" => "Bearer",
                "refreshToken" => $token,
                "expires" => 0
            ]);
        }

        return response()->json(['message' => 'Unauthorized' ], 401);
    }

    public function userInfo()
    {
        $user = Auth::user();
        // $user->sysRoles;
        // $user->roles->pluck('code')->all();
        // $user->permissions;
        // dd($user->sysRoles->toArray());
        // dd($user->perms);
        // $user->perms;
        $user->roles = $user->sysRoles->pluck('code')->all();
        // $user->hide();
        return $this->responseSuccess($user);
    }

    public function newTest()
    {
        if (Auth::user()->tokenCan('new.test')) {
            // ...
            return $this->responseSuccess([2132312]);

        }
        return $this->responseFailed();
    }

    public function captcha()
    {
        return $this->responseSuccess(Captcha::create('math', true));
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return $this->responseSuccess();
    }
}